#!/bin/bash
MYLOGFILE="/var/www/html/start.html"
source /usr/bin/gxcc_common.sh

#保证该脚本在同一时间只能有一个执行
if (set -o noclobber;echo "nothing" > ${WEB_DIR}/${LOCK_FILE_START}) 2> /dev/null;then
    trap 'rm -f ${WEB_DIR}/${LOCK_FILE_START};exit $?' INT TERM EXIT

    echo "<!DOCTYPE html><html>" > $MYLOGFILE
    echo "<p><a href=\"index.html\" target=\"_blank\"><b>本节点：${THIS_NODE_IP}</b></a></p>" >> $MYLOGFILE
    echo "<p><b>脚本名称：${BASH_SOURCE[0]}</b></p>" >> $MYLOGFILE
    echo "<p><b>执行时间：$(date "+%Y-%m-%d %H:%M:%S")</b></p>" >> $MYLOGFILE

    if [ `whoami` != "root" ];then echo "<p>须以root用户执行，执行结束</p></html>" >> $MYLOGFILE;exit 1;fi
    if ! check_this_node_ip $MYLOGFILE;then echo "<p>本节点IP设置错误，执行结束</p></html>" >> $MYLOGFILE;exit 1;fi
    echo "<p>检查本节点、另一节点是否RUNNING，另一节点是否存在${WEB_DIR}/${LOCK_FILE_START}</p>" >> $MYLOGFILE
    if check_this_node_running $MYLOGFILE;then echo "<p>执行结束</p></html>" >> $MYLOGFILE;exit 1;fi
    if check_another_node_running $MYLOGFILE $ANOTHER_NODE_IP;then echo "<p>执行结束</p></html>" >> $MYLOGFILE;exit 1;fi
    if check_another_node_locking $MYLOGFILE $ANOTHER_NODE_IP;then echo "<p>执行结束</p></html>" >> $MYLOGFILE;exit 1;fi
    
    check_another_node_stopped $MYLOGFILE $ANOTHER_NODE_IP
    if [ $? -eq 0 ];then
	echo "<p>在另一节点状态页面检测到STOPPED状态，可以启动本节点</p>" >> $MYLOGFILE
	start_this_node_with_check $MYLOGFILE
	if [ $? -eq 0 ];then
	    echo "<p>本节点：启动成功</p>" >> $MYLOGFILE
	    echo "<p>STATE:RUNNING/$(date "+%Y-%m-%d %H:%M:%S")</p>" >> $MYLOGFILE
	else
	    echo "<p>本节点：启动异常</p>" >> $MYLOGFILE
	fi
    else
	echo "<p>没有在另一节点状态页面检测到STOPPED状态</p>" >> $MYLOGFILE
	check_connect_this_node
	if [ $? -eq 0 ];then
	    echo "<p>本节点网络：可达</p>" >> $MYLOGFILE
	    check_connect_another_node $ANOTHER_NODE_IP
	    if [ $? -eq 0 ];then
		echo "<p>另一节点网络：可达，不允许启动</p>" >> $MYLOGFILE
	    else
		echo "<p>另一节点网络：不可达，允许启动</p>" >> $MYLOGFILE
		start_this_node_with_check $MYLOGFILE
		if [ $? -eq 0 ];then
		    echo "<p>本节点：启动成功</p>" >> $MYLOGFILE
		    echo "<p>STATE:RUNNING/$(date "+%Y-%m-%d %H:%M:%S")</p>" >> $MYLOGFILE
		else
		    echo "<p>本节点：启动异常</p>" >> $MYLOGFILE
		fi
	    fi
	else
	    echo "<p>本节点网络：不可达，不允许启动</p>" >> $MYLOGFILE
	fi
    fi
    
    echo "<p>执行结束</p></html>" >> $MYLOGFILE
    cp $MYLOGFILE /var/www/html/index.html
else
    echo "重复执行"
fi
